﻿#region MIT

//  /*The MIT License (MIT)
// 
//  Copyright 2016 lizs lizs4ever@163.com
//  
//  Permission is hereby granted, free of charge, to any person obtaining a copy
//  of this software and associated documentation files (the "Software"), to deal
//  in the Software without restriction, including without limitation the rights
//  to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
//  copies of the Software, and to permit persons to whom the Software is
//  furnished to do so, subject to the following conditions:
//  
//  The above copyright notice and this permission notice shall be included in
//  all copies or substantial portions of the Software.
//  
//  THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
//  IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
//  FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
//  AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
//  LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
//  OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
//  THE SOFTWARE.
//   * */

#endregion

using System;
using System.Collections.Generic;
using System.Linq;
#if NET35
#else
using System.Threading.Tasks;

#endif

namespace mom
{
    /// <summary>
    ///     time scheduler
    /// </summary>
    public sealed class Scheduler
    {
        private readonly Dictionary<Action, TimerWrapper> _timers = new Dictionary<Action, TimerWrapper>();

        /// <summary>
        ///     stop all timers
        /// </summary>
        public void Stop()
        {
            foreach (var timer in _timers.Select(x => x.Value))
                timer.Stop();
            _timers.Clear();
        }

        /// <summary>
        ///     取消回调
        /// </summary>
        /// <param name="action"></param>
        public void Stop(Action action)
        {
            var timer = Get(action);
            if (timer == null) return;

            timer.Stop();
            _timers.Remove(action);
        }

#if NET35
#else
        /// <summary>
        ///     等待
        /// </summary>
        /// <param name="duration"></param>
        /// <returns></returns>
        public Task<bool> Wait(uint duration)
        {
            var cs = new TaskCompletionSource<bool>();
            Invoke(() => { cs.SetResult(true); }, duration);

            return cs.Task;
        }
#endif

        /// <summary>
        ///     在delay之后回调，并每隔period回调
        /// </summary>
        /// <param name="action"></param>
        /// <param name="delay"></param>
        /// <param name="period"></param>
        public void Invoke(Action action, uint delay, uint period)
        {
            Stop(action);

            var timer = TimerWrapper.Create(action, delay, period);
            _timers.Add(action, timer);
            timer.Start();
        }

        /// <summary>
        ///     在delay ms之后回调
        /// </summary>
        /// <param name="action"></param>
        /// <param name="delay"></param>
        public void Invoke(Action action, uint delay)
        {
            Stop(action);

            var timer = TimerWrapper.Create(action, delay);
            _timers.Add(action, timer);
            timer.Start();
        }

        /// <summary>
        ///     在time时间回调
        /// </summary>
        /// <param name="action"></param>
        /// <param name="time"></param>
        public void Invoke(Action action, DateTime time)
        {
            var now = DateTime.Now;
            if (time < now)
            {
                Logger.Ins.Error("Attempt to invoke action before now!!!");
                return;
            }

            Invoke(action, (uint) (time - now).TotalMilliseconds);
        }

        /// <summary>
        ///     修改Delay/Period
        ///     仅针对重复性定时器
        /// </summary>
        /// <param name="action"></param>
        /// <param name="period"></param>
        public bool ResetPeriod(Action action, uint period)
        {
            var timer = Get(action);
            if (timer == null || !timer.Repeated) return false;

            Stop(action);

            // 重新计算delay
            uint delay;
            if (timer.Invoked)
            {
                delay = (uint) (timer.Elapsed - timer.Delay)%period;
            }
            else
            {
                delay = (uint) timer.Elapsed - timer.Delay;
            }

            // 重新调度
            Invoke(action, delay, period);
            return true;
        }

        /// <summary>
        ///     修改延时执行时间
        ///     针对单次定时器
        /// </summary>
        /// <param name="action"></param>
        /// <param name="delay"></param>
        public bool ResetDelay(Action action, uint delay)
        {
            var timer = Get(action);
            if (timer == null || timer.Repeated) return false;

            if (timer.Invoked)
                return false;

            Stop(action);
            var newDelay = delay - timer.Elapsed;
            if (newDelay < 0)
                newDelay = 0;

            Invoke(action, (uint) newDelay);
            return true;
        }

        /// <summary>
        ///     根据Action获取TimerWrapper
        /// </summary>
        /// <param name="action"></param>
        /// <returns></returns>
        public TimerWrapper Get(Action action)
        {
            return !_timers.ContainsKey(action) ? null : _timers[action];
        }

        /// <summary>
        ///     是否存在某个调度
        /// </summary>
        /// <param name="action"></param>
        /// <returns></returns>
        public bool Contains(Action action)
        {
            return Get(action) != null;
        }
    }
}
